import Vue from 'vue'
import Router from 'vue-router'
import routes from './modules'
import whiteList from './whiteList'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.NODE_ENV === 'development' ? process.env.BASE_URL : '/gosun-smart/',
  routes
})
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const allPath = localStorage.getItem('menus')
  let allPathArr = []
  if (allPath) {
    // 本地存储的所有路径字符串转数组
    allPathArr = allPath.split(',')
  }
  if (to.path.indexOf('/login') !== -1) {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('toPath')
    localStorage.removeItem('store')
    localStorage.removeItem('userMenus')
    localStorage.removeItem('menus')
    next()
  } else {
    // 公告详情没有登录也可以访问
    if (token || to.path === '/my/notify/detail' || to.path === '/auth-login') {
      if (allPathArr.includes(to.path) || whiteList.includes(to.path)) {
        next()
      } else {
        Vue.prototype.$toast('暂无权限')
        next(false)
      }
    } else {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('toPath')
      localStorage.removeItem('store')
      localStorage.removeItem('userMenus')
      localStorage.removeItem('menus')
      next('/login')
    }
  }
})

router.afterEach((to, from) => {
  // 用于判断当前页面，用户双击返回判断
  localStorage.setItem('toPath', to.path)
})

export default router
